﻿using Zws.Common.ScanTool;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Zws.Frameworker.Module;

namespace Zws.Frameworker.Extensions
{
    public static class WebApplicationBuilderExtension
    {
        /// <summary>
        /// 模块加载
        /// </summary>
        /// <param name="builder"></param>
        public static void LoadModule(this WebApplicationBuilder builder)
        {
            var types = ScanHelper.ScanSpecialPublicClassByAssemblys(type => type.IsAssignableTo(typeof(ModuleMark)));
            if (types.Count == 0) return;
            //模块注册
            foreach (var type in types)
            {
                builder.Services.AddSingleton(typeof(ModuleMark), type);
            }
        }
        public static void ExecModule(this WebApplicationBuilder builder)
        {
            var sp = builder.Services.BuildServiceProvider();
            var modules = sp.GetService<IEnumerable<ModuleMark>>();
            //模块排序
            if (modules == null) return;
            foreach (var module in modules)
            {
                module.OnBuilderExec(builder);
            }
        }
        public static void LoadAndExecModule(this WebApplicationBuilder builder)
        {
            builder.LoadModule();
            builder.ExecModule();
        }

    }
}
